App.require(function () {
    var app = App.getCurrent();

    app.definePage("index", {
        render: function (next) {
            this.fetchAll(["./form.html", "./index.html"], function (textList) {
                this.data.formHtml = textList[0];
                next(this.renderHTML(textList[1]));
            })
        },
        getDomObj: function () {
            this.attachDom("#viewer", "viewer")
                .attachDom("#headerBtns", "headerBtn")
                .attachEvent("headerBtn", "headerbtnclick", this.headerBtnClickHandler, false)
                .attachDom("#form-container", "formContainer")
                .attachEvent("formContainer", "inputChange", this.changeHandler, false)
                .attachDom("#sceneManager", "sceneManager")
                .attachEvent("sceneManager", "sceneplus", this.sceneOperationHandler, false)
                .attachEvent("sceneManager", "scenedelete", this.sceneDeleteHandler, false)
                .attachEvent("sceneManager", "itemclick", this.itemClickHandler, false)
                .attachEvent("viewer", "dragover", this.dragOverHandler, false)
                .attachEvent("viewer", "dragenter", this.dragEnterHandler, false)
                .attachEvent("viewer", "dragleave", this.dragLeaveHandler, false)
                .attachEvent("viewer", "drop", this.dropHandler, false)
                .attachEvent("viewer", "edit", this.editHandler, false)
                .attachDiyEvent("renderscene", this.renderSceneHandler)
                .attachDiyEvent("previewScene", this.previewSceneHandler)
                .attachEvent("viewer", "removewidget", this.removeWidgetHandler, false);
        },
        headerBtnClickHandler: function (ev) {
            var component = ev.detail.btnComponent;
            switch (component.dataset.action) {
                case "preview":
                    this.domList.sceneManager.getSceneList(function (list) {
                        app.showPageDialog("previewSceneSelect", {
                            mask: true,
                            maskCancel: true,
                            scenes: list,
                            cssString: "--startstatus: translateY(100%);--endstatus: translateY(0);left: 20px; right: 20px; top: 40px; bottom: 40px; padding: 16px;flex: 1; display: flex;"
                        });
                    })
                    break;
                case "backpreview":
                    this.domList.viewer.backPreview();
                    break;
                case "save":
                    var currentScene =this.domList.viewer.currentScene;
                    currentScene.toObject(function (obj) {
                        this.domList.sceneManager.saveScene(obj);
                    }.bind(this))
                    break;
                case "create":
                    this.domList.sceneManager.getSceneList(function (list) {
                        app.showPageDialog("createViewer", {
                            mask: true,
                            maskCancel: true,
                            scenes: list,
                            cssString: "--startstatus: translateY(100%);--endstatus: translateY(0);left: 20px; right: 20px; top: 40px; bottom: 40px; padding: 16px;flex: 1; display: flex;"
                        });
                    })
                    break;
                default: break;
            }
        },
        changeHandler: function (ev) {
            var detail = ev.detail,
                component = detail.component,
                behavior = detail.behavior,
                value = detail.value,
                key = detail.key;

            var detail = this._getBehavior(this.eventTarget.data, behavior);
            detail[key].callback.call(this.eventTarget.widget, key, value, component);
        },
        _getBehavior: function (target, key) {
            for (var i = 0; i < target.length; i++) {
                if (target[i].name == key) return target[i].detail;
            }
        },
        sceneOperationHandler: function (ev) {
            app.showPageDialog('cSelectScene', {
                mask: true,
                maskCancel: true,
                cssString: "--startstatus: translateY(100%);--endstatus: translateY(0);left: 20px; right: 20px; top: 40px; bottom: 40px; padding: 16px;flex: 1; display: flex;"
            });
        },
        sceneDeleteHandler: function (ev) {
            var viewer =this.domList.viewer;
            viewer.removeScene(ev.detail.uid);
            viewer.renderScene(ev.detail.activeScene);
        },
        itemClickHandler: function (ev) {
            if (this.eventTarget) {
                var that = this;
                this.innerHTML(this.domList.formContainer, "", function () {
                    that.eventTarget = null;
                })
            }
           this.domList.viewer.renderScene(ev.detail.scene);
        },
        deleteAndRenderSceneHandler: function (ev) {
            var viewer =this.domList.viewer;
            viewer.removeScene(ev.uid);
            viewer.renderScene(ev.activeScene);
        },
        previewSceneHandler: function (ev) {
           this.domList.viewer.previewScene(ev.scenes, app.wm, app.wbm);
            ev.popup.hidden();
        },
        renderSceneHandler: function (ev) {
            var scene =this.domList.viewer.renderScene(ev.scene, app.wm, app.wbm);
            scene.title = ev.scene.title;
            scene.url = ev.scene.url;
            scene.description = ev.scene.description;
            this.domList.sceneManager.addScene(scene);
            ev.popup.hidden();
        },
        removeWidgetHandler: function (ev) {
            var widget = ev.detail.widget;
            if (this.eventTarget && this.eventTarget.widget === widget) {
                var that = this;
                this.innerHTML(this.domList.formContainer, "", function () {
                    that.eventTarget = null;
                })
            }
        },
        dragOverHandler: function (ev) {
            ev.stopPropagation();
            ev.preventDefault();
            ev.dataTransfer.dropEffect = 'copy';
            return false;
        },
        dragEnterHandler: function (ev) {
            ev.stopPropagation();
            ev.preventDefault();
            return false;
        },
        dragLeaveHandler: function (ev) {
            return false;
        },
        dropHandler: function (ev) {
            ev.dataTransfer.dropEffect = 'copy';
            ev.preventDefault();
            ev.stopPropagation();

            var target = ev.target;
            var text = ev.dataTransfer.getData("text/plain");
            var fileList = ev.dataTransfer.files;
            var rect = target.getBoundingClientRect(), cx = ev.clientX, cy = ev.clientY;
            if (text) {
                var widget = app.wm.addWidget(text, {
                    x: cx - rect.left, y : cy - rect.top
                },this.domList.viewer.currentScene);
                app.wbm.addBehavior("active", {}, widget);
                app.wbm.addBehavior("remove", {}, widget);
                app.wbm.addBehavior("pos", {}, widget);
                if ("initBehaviors" in widget) {
                    var initBehaviors = widget.initBehaviors;
                    for (var i = 0; i < initBehaviors.length; i++) {
                        var b = initBehaviors[i];
                        app.wbm.addBehavior(b.name, b.style, widget);
                        if ("initStyle" in b) {
                            for (var key in b.initStyle) {
                                widget[key] = b.initStyle[key];
                            }
                        }
                    }
                }
            }
            if (fileList.length > 0) {

            }
        },
        editHandler: function (ev) {
            var container = this.domList.formContainer, that = this, widget = ev.detail.widget;
            this.innerHTML(container, this.data.formHtml, function () {
                that.eventTarget = ev.detail;
                if (that.activeWidget) that.activeWidget.updatePropertyElement({});
                that.activeWidget = widget;
                var obj = that.attachEventByProperty(ev.detail.data, container);
                widget.updatePropertyElement(obj);
            }, { data: this.computeData(ev.detail.data, widget) });
        },
        attachEventByProperty: function (data, container) {
            var result = {};
            for (var i = 0; i < data.length; i++) {
                var item = data[i], detail = item.detail, name = item.name;
                var parentDom = container.querySelector("[data-behavior='" + name + "']");
                if (parentDom) {
                    for (var key in detail) {
                        var keyElement = parentDom.querySelector("[data-key='" + key + "']");
                        if (keyElement) {
                            if (keyElement.dataset.type == "component") keyElement = this._getComponentByDom(keyElement);
                            if (key in result) {
                                result[key].push(keyElement);
                            }
                            else {
                                result[key] = [keyElement];
                            }
                        }
                    }
                }
            }
            return result;
        },
        computeData: function (data, target) {
            var result = [];
            for (var i = 0; i < data.length; i++) {
                var d = data[i], behavior = d.behavior;
                var obj = { name: d.name, detail: [] };
                for (var key in d.detail) {
                    obj.detail.push({
                        name: key,
                        value: d.detail[key].initValue.call(target),
                        element: d.detail[key].element.call(behavior)
                    })
                }
                result.push(obj);
            }
            return result;
        },
        init: function () {
            var viewer =this.domList.viewer = App.Viewer.create(this.domList.viewer, { width: 960, height: 540 }, app.sm, "index", { })
            viewer.currentScene.title = "初始页";
            this.domList.sceneManager.addScene(viewer.currentScene);
            // var rect = app.wm.addWidget("rect", {
            //     width: 200,
            //     height: 300,
            //     stroke: "black",
            //     fill: "green",
            //     x: 100.5,
            //     y: 200.5,
            //     isEdit: true
            // }, viewer.currentScene);

            // var innerRect = app.wm.addWidget("rect", {
            //     // width: 100,
            //     // height: 100,
            //     // stroke: "gray",
            //     // fill: "indigo",
            //     // x: 25.5,
            //     // y: 25.5,
            //     // isEdit: true
            // }, rect);

            // var line = app.wm.addWidget("polyline", {
            //     points: [ 20.5, 20.5, 20.5, 80.5 ],
            //     stroke: "black",
            // }, viewer.currentScene);
            // app.wm.addWidget("polyline", {
            //     points: [ 20.5, 20.5, 80.5, 20.5 ],
            //     stroke: "black",
            // }, viewer.currentScene);

            // app.wm.addWidget("polyline", {
            //     points: [ 17.5, 77.5, 20.5, 80.5, 23.5, 77.5 ], 
            //     stroke: "red"
            // }, viewer.currentScene);
            // app.wm.addWidget("polyline", {
            //     points: [ 77.5, 17.5, 80.5, 20.5, 77.5, 23.5 ], 
            //     stroke: "red"
            // }, viewer.currentScene);
            // var polyline = app.wm.addWidget("polyline", {
            //     stroke: "gray",
            //     points: [ 20.5, 35, 30.5, 40, 40.5, 48, 50.5, 56, 60.5, 52, 70.5, 72, 80.5, 52]
            // }, viewer.currentScene);
            // app.wm.addWidget("line", {
            //     x1: 20, y1: 20, x2: 100, y2: 100, stroke: "red", opacity: 0.5
            // }, viewer.currentScene);
            // app.wm.addWidget("arc", {
            //     x: 100, y: 100, r: 20, stroke: "red", opacity: 0.5, endAngle: Math.PI 
            // }, viewer.currentScene);
            // app.wm.addWidget("earc", {
            //     x: 100, y: 150, rx: 40, ry: 30, stroke: "red", opacity: 0.5, endAngle: Math.PI 
            // }, viewer.currentScene);
            // app.wm.addWidget("image", {
            //     url: "/public/ui/img/qst.png"
            // }, viewer.currentScene);
            // app.wm.addWidget("column", {
            //     x: 300,y: 200, fill: "orange", distance: 30, option: [ {value: 100}, {value: 50}, {value: 75} ]
            // }, viewer.currentScene);
            // app.wm.addWidget("linechart", {
            //     x: 300,y: 200, fill: "orange", distance: 30, option: [ {value: 100}, {value: 50}, {value: 75} ]
            // }, viewer.currentScene);
            // app.wm.addWidget("pie", {
            //     ir: 50, or: 150, x: 300,y: 400, fill: "orange", distance: 30, option: [ {offset: 3, value: 100, fill: "black"}, {value: 50}, {value: 75, fill: "red"} ]
            // }, viewer.currentScene);
            // app.wm.addWidget("radar", {
            //     x: 120, y: 300,
            //     option: [ { value: 100 }, {value: 50}, {value: 75 }, { value: 60 }, { value: 80 } ]
            // }, viewer.currentScene);

            // app.wm.addWidget("polygon", {
            //     points: [{ x: 100, y: 100}, { x: 150, y: 150 }, { x: 50, y: 150 }],
            //     stroke: "red"
            // }, viewer.currentScene);
            // app.wm.addWidget("rectangle", {
            //     fill: "orange",
            //     x: 150, y: 140,
            //     stroke: "red"
            // }, viewer.currentScene);
            // app.wm.addWidget("path", {
            //     fill: "rgba(228, 255, 123, 0.5)",
            //     path: "M 100 60 L 200 60 L 200 200 L 100 200 Z",
            //     stroke: "red"
            // }, viewer.currentScene);
            // app.wm.addWidget("text", {
            //     fill: "rgba(228, 255, 123, 0.8)",
            //     text: "text组件",
            //     font: "28px arial",
            //     stroke: "red",
            //     x: 300, y: 250
            // }, viewer.currentScene);
            // app.wm.addWidget("scatter", {
            //     fill: "red",
            //     stroke: "black",
            //     x: 400, y: 400,
            //     option: [{offset: 30, value: 60 }, { offset: 80, value: 80 }]
            // }, viewer.currentScene)
            // app.wm.addWidget("funnel", {
            //     fill: "red",
            //     stroke: "black",
            //     x: 200, y: 400,
            //     option: [{value: 160 }, {value: 80 }]
            // }, viewer.currentScene)
            // app.wm.addWidget("axis", {
            //     stroke: "black",
            //     width: 250, height: 250,
            //     x: 100, y: 500
            // }, viewer.currentScene)
            
            // app.wbm.addBehavior("position", {
            //     stroke: "black", fill: "red", radius: 5
            // }, rect);

            // app.wbm.addBehavior("rotate", {}, rect);

            // app.wbm.addBehavior("position", {
            //     stroke: "black", fill: "red", radius: 5
            // }, innerRect);

            // app.wbm.addBehavior("rotate", {}, innerRect);
            // app.wbm.addBehavior("polylineB", {}, polyline);
            // app.wbm.addBehavior("fill", {}, polyline);
        },
        filter: {
            json: function (data) {
                return JSON.stringify(data);
            }
        }
    })
})